/**
 * 
 */
package wong.board.client.ui;

import java.util.ArrayList;

import wong.board.client.ui.ShowcasesPresenter.View;
import wong.board.client.widgets.ContentContainer;
import wong.board.client.widgets.Link;
import wong.board.client.widgets.Table;
import wong.board.shared.ContentKeys;

import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Label;

/**
 * @author wong
 * 
 */
public class ShowcasesView extends ContentContainer implements View {

	private Table table;

	/**
	 * @param text
	 */
	public ShowcasesView() {
		super(ContentKeys.Showcases.toString());
		addStyleName(boardCss.showcases());
		table = new Table();
		table.addStyleName(boardCss.showcaseTable());
		getContent().add(table);
	}

	@Override
	public void setData(Data data) {
		table.clear();

		int rowCount = data.rows.size();
		int colCount = data.columns.size();

		ArrayList<IsWidget> header = new ArrayList<IsWidget>();
		header.add(createHeader("", boardCss.showcaseEnvironment()));
		for (String columnTitle : data.columns) {
			header.add(createHeader(columnTitle, boardCss.showcaseEnvironment()));
		}
		table.addRowData(header.toArray(new IsWidget[header.size()])).asWidget()
				.addStyleName(boardCss.showcaseHeader());

		for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
			String rowTitle = data.rows.get(rowIndex);
			ArrayList<ArrayList<Data.LinkInfo>> rowData = data.getRow(rowIndex);
			table.addRowData(createDataRow(rowTitle, rowData, colCount)).asWidget()
					.addStyleName(boardCss.showcaseRow());
		}

	}

	protected IsWidget createHeader(String text, String style) {
		Label header = new Label(text);
		header.setStyleName(style);
		return header;
	}

	protected FlowPanel createData(String style) {
		FlowPanel data = new FlowPanel();
		data.setStyleName(style);
		return data;
	}

	protected IsWidget[] createDataRow(String title, ArrayList<ArrayList<Data.LinkInfo>> rowData, int colCount) {
		ArrayList<IsWidget> rowDataList = new ArrayList<IsWidget>();
		IsWidget type = createHeader(title, boardCss.showcaseType());
		type.asWidget().addStyleName(boardCss.showcaseCell());
		rowDataList.add(type);
		for (int col = 0; col < colCount; col++) {
			FlowPanel data = createData(boardCss.showcaseLinks());
			data.addStyleName(boardCss.showcaseCell());
			rowDataList.add(data);
			if (col < rowData.size()) {
				ArrayList<Data.LinkInfo> cell = rowData.get(col);
				for (Data.LinkInfo linkInfo : cell) {
					Link link = new Link(linkInfo.label, linkInfo.link, linkInfo.tooltip);
					link.addStyleName(boardCss.showcaseLink());
					data.add(link);
					// data.getElement().appendChild(Document.get().createBRElement());
				}
			}
		}
		return rowDataList.toArray(new IsWidget[rowDataList.size()]);
	}

}
